﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Models.InputModels;

namespace Xoohoo.Modules.Membership.ModelBinders
{
    public class RoleInputModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProvider = bindingContext.ValueProvider;

            Guid tmpGuid;
            Guid? roleID = null;
            if (valueProvider.GetAttemptedValue("roleID").GuidTryParse(out tmpGuid))
                roleID = tmpGuid;

            string roleName = valueProvider.GetAttemptedValue("RoleName");
            string permissions = valueProvider.GetAttemptedValue("Permissions");
            IEnumerable<Guid> permissionIDList = Enumerable.Empty<Guid>();
            if (!String.IsNullOrEmpty(valueProvider.GetAttemptedValue("Permissions")))
            {
                string[] permissionArray = valueProvider.GetAttemptedValue("Permissions").Split(',');

                permissionIDList = from s in permissionArray
                                   where s.IsGuid()
                                   select new Guid(s);
            }
            return new RoleInput{
                RoleID = roleID,
                RoleName = roleName,
                Permissions = permissionIDList
            };
        }
    }
}
